package DataStuctures;

import DataStuctures.LinkList.LinkListDummyHead_Delete;

public class LinklistTest<E> {

    private Node dummyHead;
    private int size;



    public LinklistTest() {
        dummyHead = new Node(null,null);
        size = 0;
    }

    private class Node{
        public E e;
        public Node next;

        public Node(E e,Node next) {
            this.e = e;
            this.next = next;
        }

        public Node() {
            this(null,null);
        }

        public Node(E e) {
            this(e,null );
        }

        @Override
        public String toString() {
            return e.toString();
        }
    }


    public int getSize(){
        return size;
    }

    public boolean isEmpty(){
        return size == 0;
    }

    public void add(E e,int index){

        if(index < 0 || index > size){
            throw new IllegalArgumentException("Add Failed,index is illegal");
        }

        //Node prev = dummyHead.next;  //这样会导致空指针，因为根本没有下一个节点
        Node prev = dummyHead;
        for (int i = 0; i < index; i++) {
            prev = prev.next;
        }
        Node node = new Node(e);
        node.next = prev.next;
        prev.next = node;
        size++;
    }

    public void addFirst(E e){
        add(e,0);
    }

    public void addLast(E e){
        add(e,size);
    }

    public void remove(int index){

        if(index < 0 || index > size){
            throw new IllegalArgumentException("Add Failed,index is illegal");
        }

        Node prev = dummyHead;
        for (int i = 0; i < index; i++) {
            prev = prev.next;
        }
        Node retNode = prev.next;
        prev.next = retNode.next;
        retNode.next = null;
        size--;
    }


    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        LinklistTest.Node cur = dummyHead.next;
        while (cur != null){
            res.append(cur + "->");
            cur = cur.next;
        }
        res.append("NULL");
        return res.toString();
    }


    public static void main(String[] args) {
        LinklistTest<Integer> list = new LinklistTest<>();
        for (int i = 0; i < 5; i++) {
            list.addFirst(i);
        }
        System.out.println(list);

        list.remove(2);
        System.out.println(list);
    }
}
